import { Injectable } from '@nestjs/common';
import { CreateBookInfoDto } from './dto/create-book-info.dto';
import { UpdateBookInfoDto } from './dto/update-book-info.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { BookInfo } from './entities/book-info.entity';

@Injectable()
export class BookInfoService {
  constructor(
    @InjectRepository(BookInfo) private bookRepository: Repository<BookInfo>,
  ) {}

  /**
   * create book information
   * @param createBookInfoDto
   */
  create(createBookInfoDto: CreateBookInfoDto) {
    const newBookInfo: BookInfo = new BookInfo();
    newBookInfo.dynasty = createBookInfoDto.dynasty;
    newBookInfo.yearTitle = createBookInfoDto.yearTitle;
    newBookInfo.bookName = createBookInfoDto.bookName;
    newBookInfo.author = createBookInfoDto.author;
    newBookInfo.totalVolume = createBookInfoDto.totalVolume;
    newBookInfo.volume = createBookInfoDto.volume;
    newBookInfo.volumeName = createBookInfoDto.volumeName;
    newBookInfo.context = createBookInfoDto.context;
    newBookInfo.page = createBookInfoDto.page;

    return this.bookRepository.save(newBookInfo);
  }

  /**
   * findManyFromMatchFlagAndInfo
   * @param matchFlag {string}
   * @param info {string}
   * @param convertedInfo {string}
   */
  findManyFromMatchFlagAndInfo(
    matchFlag: string,
    info: string,
    convertedInfo: string,
  ) {
    return this.bookRepository
      .createQueryBuilder('aBook')
      .where(
        `aBook.${JSON.stringify(matchFlag).substring(
          1,
          JSON.stringify(matchFlag).length - 1,
        )} like :param`,
      )
      .setParameters({
        param: '%' + info + '%',
      })
      .orWhere(
        `aBook.${JSON.stringify(matchFlag).substring(
          1,
          JSON.stringify(matchFlag).length - 1,
        )} like :param2`,
      )
      .setParameters({
        param2: '%' + convertedInfo + '%',
      })
      .getMany();
  }

  findAll() {
    return `This action returns all bookInfo`;
  }

  findOne(id: number) {
    return `This action returns a #${id} bookInfo`;
  }

  update(id: number, updateBookInfoDto: UpdateBookInfoDto) {
    return `This action updates a #${id} bookInfo`;
  }

  remove(id: number) {
    return `This action removes a #${id} bookInfo`;
  }
}
